package com.tssf.car_manage.controller;

import com.tssf.car_manage.entity.Admin;
import com.tssf.car_manage.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller

public class AdminRegisterController {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    // 显示注册页面
    @GetMapping("/register")
    public String showRegisterPage() {
        return "register";
    }

    // 发送验证码（存储到Redis）
    @GetMapping("/sendCaptcha")
    @ResponseBody
    public Map<String, Object> sendCaptcha(@RequestParam String username) {
        Map<String, Object> result = new HashMap<>();

        // 检查用户名是否已存在
        if (adminMapper.getAdminByUsername(username).size() > 0) {
            result.put("success", false);
            result.put("message", "用户名已存在");
            return result;
        }

        // 检查是否已有未过期的验证码
        String existingCaptcha = redisTemplate.opsForValue().get("register:captcha:" + username);
        if (existingCaptcha != null) {
            result.put("success", false);
            result.put("message", "验证码已发送，请勿频繁请求");
            return result;
        }

        // 生成6位随机验证码
        String captcha = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        System.out.println(captcha);
        try {
            // 存储到Redis，有效期5分钟
            redisTemplate.opsForValue().set(
                    "register:captcha:" + username,
                    captcha,
                    5,
                    TimeUnit.MINUTES
            );

            // 模拟发送验证码
            System.out.println("发送验证码：" + captcha + " 到用户：" + username);

            result.put("success", true);
            // 正式环境应移除下面这行
            result.put("captcha", captcha);
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "验证码发送失败: " + e.getMessage());
            return result;
        }
    }

    @PostMapping("/register")
    public String registerAdmin(
            @RequestParam String username,
            @RequestParam String email,
            @RequestParam String password,
            @RequestParam String confirmPassword,
            @RequestParam String captcha,
            @RequestParam(required = false, defaultValue = "0") Integer role,
            Model model) {

        // 基本验证
        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "两次输入的密码不一致");
            return "register";
        }

        // 检查用户名是否已存在
        if (adminMapper.getAdminByUsername(username).size() > 0) {
            model.addAttribute("error", "用户名已存在");
            return "register";
        }

        try {
            // 验证码校验
            String storedCaptcha = redisTemplate.opsForValue().get("register:captcha:" + username);
            if (storedCaptcha == null || !storedCaptcha.equals(captcha)) {
                model.addAttribute("error", "验证码错误或已过期");
                return "register";
            }

            // 注册管理员
            Admin admin = new Admin();
            admin.setUsername(username);
            admin.setPassword(password);
            admin.setEmail(email);
            admin.setRole(role != null ? role : 0);

            adminMapper.save(admin);

            // 确保删除验证码
            try {
                redisTemplate.delete("register:captcha:" + username);
            } catch (Exception e) {
                System.err.println("删除验证码失败: " + e.getMessage());
            }

            model.addAttribute("success", "管理员注册成功");
            return "redirect:/login";
        } catch (Exception e) {
            model.addAttribute("error", "注册失败: " + e.getMessage());
            return "register";
        }
    }
}